// TowerHealth.cs
using UnityEngine;
using UnityEngine.UI;

public class TowerHealth : MonoBehaviour
{
    public float maxHealth = 10000f;  // 初始生命值
    private float currentHealth;  // 当前生命值
    public Slider healthSlider; // 血条Slider
    public float decreaseRate = 10f; // 生命值减少速率

    private void Start()
    {
        currentHealth = maxHealth;

        // 检查是否有血条Slider引用
        if (healthSlider != null)
        {
            healthSlider.maxValue = maxHealth;
            healthSlider.value = currentHealth;
        }
    }

    private void Update()
    {
        // 随时间减少生命值
        DecreaseHealthOverTime();
    }

    private void OnTriggerEnter(Collider other)
    {
        // 减少生命值，不论碰撞的是什么类型的对象
        TakeDamage(1000);  // 减少100生命值

        // 在这里可以添加其他处理碰撞的逻辑
    }

    private void TakeDamage(float damage)
    {
        // 减少生命值
        currentHealth -= damage;

        // 更新血条的值
        if (healthSlider != null)
        {
            healthSlider.value = currentHealth;
        }

        // 如果生命值小于等于0，则销毁塔
        if (currentHealth <= 0)
        {
            Destroy(gameObject);
        }
    }

    private void DecreaseHealthOverTime()
    {
        // 随时间减少生命值
        currentHealth -= decreaseRate * Time.deltaTime;

        // 更新血条的值
        if (healthSlider != null)
        {
            healthSlider.value = currentHealth;
        }

        // 如果生命值小于等于0，则销毁塔
        if (currentHealth <= 0)
        {
            Destroy(gameObject);
        }
    }
}
